//
//  TTPicCollectionView.swift
//  NewWeiBo
//
//  Created by 吴天益 on 2017/7/28.
//  Copyright © 2017年 ttt. All rights reserved.
//

import UIKit
import SnapKit
import YYWebImage

//  每项的间距
private let ItemMargin: CGFloat = 5
//  每项的宽度
private let ItemWidth: CGFloat = (ScreenWidth - 2 * HomeCellMargin - 2 * ItemMargin) / 3


class TTPicCollectionView: UICollectionView,UICollectionViewDataSource {

   

    var picArray: [TTPicURLStrModel]? {
        didSet{
            
            numLable.text = "\(picArray?.count ?? 0)"
            
            buildItemSizeAndViewSize()
     
            //刷新界面
            reloadData()
        }
    }
    
    //懒加载图片数量lable
    private lazy var numLable: UILabel = {
        let lable = UILabel()
        
        lable.font = UIFont.systemFont(ofSize: 18)
        
        lable.textColor = UIColor.white
        
        return lable
    }()
    

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSize(width: 40, height: 40)
        
        flowLayout.minimumLineSpacing = ItemMargin-1
        flowLayout.minimumInteritemSpacing = ItemMargin-1
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 界面设置
    func setupUI() {
        
        addSubview(numLable)
        numLable.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
        
        self.dataSource = self
        
        
        self.register(TTCollectionViewCell.self, forCellWithReuseIdentifier: "pic")
        
    }
    
    //MARK: - 数据源方法
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return picArray?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "pic", for: indexPath) as! TTCollectionViewCell
        
//        cell.backgroundColor = RandomColor()
        if let imageS = picArray?[indexPath.item] {
            
            cell.imageStr = imageS.thumbnail_pic
        }
        
        return cell
    }
    
    //MARK: - 计算item大小和对应的view大小
    func buildItemSizeAndViewSize() {
        
        let count = picArray?.count ?? 0
        
        //当只有一张图片时,item要按照图片的大小来显示
        if count == 1{
            
            //根据图片url字符串来获取下载好的图片
            let imageStr = picArray?.first?.thumbnail_pic
            
            if let image = YYWebImageManager.shared().cache?.getImageForKey(imageStr!){
                
                print(image.size)
                
                //如果图片太大,就给我最大值
                //  图片过窄处理
                var imageW = image.size.width
                var imageH = image.size.height
                
                if image.size.width < 80 {
                    //  图片的宽度
                    imageW = 80
                    //  图片的高度
                    imageH = imageW / image.size.width * image.size.height
                    //  过长
                    if imageH > 150 {
                        //  修改图片的高度
                        imageH = 150
                    }
                    
                }

                
                //更新view的大小
                self.snp.makeConstraints({ (make) in
                    make.size.equalTo(CGSize(width: imageW, height: imageH))
                })
                
                //如果图片太小,那么item就会比view大,所以也要约束
                let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
                flowLayout.itemSize = CGSize(width: imageW, height: imageH)
                
            }
            //如果一张图片执行到此就可以了
            return
        }
        
      
        //  计算列数
        let cols = count > 3 ? 3 : count
        //  计算行数
        let rows = (count - 1) / 3 + 1
        //  计算宽度
        let pictureViewWidth = CGFloat(cols) * ItemWidth + CGFloat(cols - 1) * ItemMargin
        //  计算高度
        let pictureViewHeight = CGFloat(rows) * ItemWidth + CGFloat(rows - 1) * ItemMargin
        
        //  更新配图大小
        self.snp.updateConstraints { (make) in
            //  提示： 更新约束的时候，如果约束有优先级那么需要在更新的时候也要设置约束优先级
            make.size.equalTo(CGSize(width: pictureViewWidth, height: pictureViewHeight)).priority(.high)
        }
        
        //  把itemsize改成图片的大小
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)

     
    }

}

//MARK: - 自定义cell的类
class TTCollectionViewCell: UICollectionViewCell {
    
    var imageStr: String?{
        didSet{
            
            if let imgStr = imageStr {
                imageView.yy_setImage(with: URL(string: imgStr), placeholder: UIImage(named: "logo"))
            }
            
        }
    }
    
    //懒加载图片
    private lazy var imageView: UIImageView = {
        
        let imgV = UIImageView(image: UIImage(named: "logo"))
        
        //按照图片原始比例等比显示
        imgV.contentMode = .scaleAspectFill
        
        //多余部分才剪掉
        imgV.clipsToBounds = true
        
        return imgV
        
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(imageView)
        
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
}
